//
//  AppDelegate.m
//  ProjectOfBStage
//
//  Created by cuixin on 15/11/11.
//  Copyright © 2015年 cuixin. All rights reserved.
//
#import "AppDelegate.h"
#import "BaseHeader.h"
#import <AVFoundation/AVFoundation.h>
#import "LDY_GuidePageViewController.h"
#import "FZ_BoFang_Two_ViewController.h"

@interface AppDelegate ()<UIScrollViewDelegate>

@property (nonatomic, retain) LDY_GuidePageViewController *guidePage;

@end

@implementation AppDelegate
-(void)dealloc{
    [_guidePage release];
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    
    // 获取沙盒版本号
    NSString *homeDirectoryVersionString = [LDY_GuidePage getHomeDirectoryVersionNumber];
    // 获取当前版本号
    NSString *atPresentVersionString = [LDY_GuidePage getAtPresentVersionNumber];
    // 若沙盒版本号与当前版本号一致, 尚未更新
    if ([homeDirectoryVersionString isEqualToString:atPresentVersionString]) {
        NSLog(@"未更新 --- 显示主页");
        [self createHomePage];
    } else {
        // 存储当前版本号
        [LDY_GuidePage saveAtPresentVersionNumber:atPresentVersionString];
        NSLog(@"更新 --- 显示引导页");
    
        self.guidePage = [[LDY_GuidePageViewController alloc] init];
        
        self.window.rootViewController = self.guidePage;
        
        [self.guidePage.guidePage.enterButton addTarget:self action:@selector(enterButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        // 背景图片
        NSArray *backgroundImagesArray = @[@"wait", @"wait", @"wait", @"wait"];
        // 滚动视图
        self.guidePage.guidePage.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.guidePage.view.frame.size.width, self.guidePage.view.frame.size.height)];
        // 分页滚动
        self.guidePage.guidePage.scrollView.pagingEnabled = YES;
        // 滚动范围
        self.guidePage.guidePage.scrollView.contentSize = CGSizeMake(self.guidePage.view.frame.size.width * backgroundImagesArray.count, 0);
        // 把滑动栏去掉
        self.guidePage.guidePage.scrollView.showsHorizontalScrollIndicator = NO;
        [self.guidePage.view addSubview:self.guidePage.guidePage.scrollView];
        // 添加背景图片
        for (int i = 0; i < backgroundImagesArray.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * self.guidePage.view.frame.size.width, 0, self.guidePage.view.frame.size.width, self.guidePage.view.frame.size.height)];
            imageView.image = [UIImage imageNamed:backgroundImagesArray[i]];
            [self.guidePage.guidePage.scrollView addSubview:imageView];
            [imageView release];
        }
        [_guidePage.guidePage.scrollView release];
        
        // 分页控制器
        self.guidePage.guidePage.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(self.guidePage.view.frame.size.width / 2 - 25, self.guidePage.view.frame.size.height - 30, 50, 20)];
        //    self.pageControl.backgroundColor = [UIColor blueColor];
        // 未选中点颜色
        self.guidePage.guidePage.pageControl.pageIndicatorTintColor = [UIColor whiteColor];
        // 当前选中点颜色
        self.guidePage.guidePage.pageControl.currentPageIndicatorTintColor = [UIColor grayColor];
        // 分页点数量
        self.guidePage.guidePage.pageControl.numberOfPages = backgroundImagesArray.count;
        [self.guidePage.view addSubview:self.guidePage.guidePage.pageControl];
        [self.guidePage.guidePage.pageControl release];
        
        self.guidePage.guidePage.scrollView.delegate = self;
        
    
    }
    
//    UITabBarController *baseTabBar = [[UITabBarController alloc] init];
//    baseTabBar.delegate = self;
    
#pragma mark 第一个tabBar （频道）
//    ChannerViewController *channerViewController = [[ChannerViewController alloc] init];
//    UINavigationController *channerNavi = [[UINavigationController alloc] initWithRootViewController:channerViewController];
//    channerNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"频道" image:[UIImage imageNamed:@"iconfont-pindao-2.png"] selectedImage:[UIImage imageNamed:@"iconfont-pindao-2.png"]];
//    
//    channerNavi.navigationBar.translucent = NO;
    
#pragma mark 第二个tabBar (阅读)
//    LDY_ReadViewController *readerViewController = [[LDY_ReadViewController alloc] init];
//    UINavigationController *readNavi = [[UINavigationController alloc] initWithRootViewController:readerViewController];
//    readNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"阅读" image:[UIImage imageNamed:@"iconfont-yuedu.png"] selectedImage:[UIImage imageNamed:@"iconfont-yuedu.png"]];
//    readNavi.navigationBar.translucent = NO;
    
    
#pragma mark 第三个tabBar（回声）
    
//    VoiceViewController *voiceViewController = [[VoiceViewController alloc] init];
//    UINavigationController *voiceNavi = [[UINavigationController alloc] initWithRootViewController:voiceViewController];
//    voiceNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"回声" image:[UIImage imageNamed:@"iconfont-yinle.png"] selectedImage:[UIImage imageNamed:@"iconfont-yinle.png"]];
//    voiceNavi.navigationBar.translucent = NO;
    
    
#pragma mark 第四个tabBar（我的）
    
//    MineViewController * mineViewController = [[MineViewController alloc] init];
//    UINavigationController *mineNavi = [[UINavigationController alloc] initWithRootViewController:mineViewController];
//    mineNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的" image:[UIImage imageNamed:@"iconfont-tongxunlu.png"] selectedImage:[UIImage imageNamed:@"iconfont-tongxunlu.png"]];
//    mineNavi.navigationBar.translucent = NO;
//    
//    baseTabBar.viewControllers = @[readNavi, channerNavi, voiceNavi, mineNavi];
//    
//    baseTabBar.tabBar.tintColor = [UIColor colorWithRed:1 green:0.37 blue:0.41 alpha:1];
//
//    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
//    [[UITabBar appearance] setBarTintColor:[UIColor whiteColor]];
//    self.window.rootViewController = baseTabBar;

    
    
//    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
//        //按位枚举 |
//        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound) categories:nil]];
//        
//        [[UIApplication sharedApplication] registerForRemoteNotifications];
//    }
//    else{
//        
//        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge |
//         UIRemoteNotificationTypeSound |
//         UIRemoteNotificationTypeAlert];
//    }

    
    
//    [channerViewController release];
//    [channerNavi release];
//    
//    [readerViewController release];
//    [readNavi release];
//    
//    [voiceViewController release];
//    [voiceNavi release];
//    
//    [mineViewController release];
//    [mineNavi release];
//    
//    [baseTabBar release];
    
    
    //后台播放
    NSError* error;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];

    return YES;
}

    
- (void)createHomePage
{
    UITabBarController *baseTabBar = [[UITabBarController alloc] init];
    //    baseTabBar.delegate = self;
    
#pragma mark 第一个tabBar （频道）
    ChannerViewController *channerViewController = [[ChannerViewController alloc] init];
    UINavigationController *channerNavi = [[UINavigationController alloc] initWithRootViewController:channerViewController];
    channerNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"频道" image:[UIImage imageNamed:@"iconfont-pindao-2.png"] selectedImage:[UIImage imageNamed:@"iconfont-pindao-2.png"]];
    
    channerNavi.navigationBar.translucent = NO;
    
#pragma mark 第二个tabBar (阅读)
    LDY_ReadViewController *readerViewController = [[LDY_ReadViewController alloc] init];
    UINavigationController *readNavi = [[UINavigationController alloc] initWithRootViewController:readerViewController];
    readNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"阅读" image:[UIImage imageNamed:@"iconfont-yuedu.png"] selectedImage:[UIImage imageNamed:@"iconfont-yuedu.png"]];
    readNavi.navigationBar.translucent = NO;
    
    
#pragma mark 第三个tabBar（回声）
    
    VoiceViewController *voiceViewController = [[VoiceViewController alloc] init];
    UINavigationController *voiceNavi = [[UINavigationController alloc] initWithRootViewController:voiceViewController];
    voiceNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"回声" image:[UIImage imageNamed:@"iconfont-yinle.png"] selectedImage:[UIImage imageNamed:@"iconfont-yinle.png"]];
    voiceNavi.navigationBar.translucent = NO;
    
    
#pragma mark 第四个tabBar（我的）
    
    MineViewController * mineViewController = [[MineViewController alloc] init];
    UINavigationController *mineNavi = [[UINavigationController alloc] initWithRootViewController:mineViewController];
    mineNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的" image:[UIImage imageNamed:@"iconfont-tongxunlu.png"] selectedImage:[UIImage imageNamed:@"iconfont-tongxunlu.png"]];
    mineNavi.navigationBar.translucent = NO;
    
    baseTabBar.viewControllers = @[readNavi, channerNavi, voiceNavi, mineNavi];
    
    baseTabBar.tabBar.tintColor = [UIColor colorWithRed:1 green:0.37 blue:0.41 alpha:1];
    
    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    [[UITabBar appearance] setBarTintColor:[UIColor whiteColor]];
    self.window.rootViewController = baseTabBar;
    
    
    //    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
    //        //按位枚举 |
    //        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound) categories:nil]];
    //
    //        [[UIApplication sharedApplication] registerForRemoteNotifications];
    //    }
    //    else{
    //
    //        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge |
    //         UIRemoteNotificationTypeSound |
    //         UIRemoteNotificationTypeAlert];
    //    }
    
    
    
    [channerViewController release];
    [channerNavi release];
    
    [readerViewController release];
    [readNavi release];
    
    [voiceViewController release];
    [voiceNavi release];
    
    [mineViewController release];
    [mineNavi release];
    
    [baseTabBar release];
}
    

/*  引导页  */
#pragma mark - Button点击事件, 移除引导页并显示主视图控制器
- (void)enterButtonAction:(UIButton *)sender
{
    NSLog(@"跳过");
    //    [self.guidePage removeFromSuperview];
    
    [self.guidePage  removeFromParentViewController];
    
    [self createHomePage];
}

#pragma mark - 滚动至最后一张图片, 移除引导页并显示主视图控制器
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.guidePage.guidePage.scrollView.contentOffset.x > self.window.frame.size.width * 3 + self.window.frame.size.width / 4) {
        //        [self.guidePage removeFromSuperview];
        
        [self.guidePage removeFromParentViewController];
        [self createHomePage];
        
    }
}

#pragma mark - 滚动视图改变, 分页点随之改变
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.guidePage.guidePage.pageControl.currentPage = self.guidePage.guidePage.scrollView.contentOffset.x / (self.guidePage.guidePage.scrollView.frame.size.width);
}


    
//-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
//    NSLog(@"%@", error);
//}


#pragma mark 后台播放
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    
    NSLog(@"\n\n倔强的打出一行字告诉你我要挂起了。。\n\n");
    
    //这段就是当音乐还在播放状态的时候，给后台权限，不在播放状态的时候，收回后台权限
    if ([FZ_BoFang_Two_ViewController sharePlayer].player.state == STKAudioPlayerStatePlaying||[FZ_BoFang_Two_ViewController sharePlayer].player.state == STKAudioPlayerStateBuffering||[FZ_BoFang_Two_ViewController sharePlayer].player.state == STKAudioPlayerStatePaused ||[FZ_BoFang_Two_ViewController sharePlayer].player.state == STKAudioPlayerStateStopped) {
        //有音乐播放时，才给后台权限，不做流氓应用。
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self becomeFirstResponder];
    }
    else
    {
        [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
        [self resignFirstResponder];
    }

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
